import React, { useState } from 'react';
import {
  Box,
  TextField,
  Button,
  CircularProgress,
  Alert,
  Grid
} from '@mui/material';
import SendIcon from '@mui/icons-material/Send';
import { processQuery } from '@/api/apiClient';
import { QueryResponse } from '@/types';

interface QueryInputProps {
  onQueryResult: (result: QueryResponse) => void;
}

const QueryInput: React.FC<QueryInputProps> = ({ onQueryResult }) => {
  const [query, setQuery] = useState('查询每个岗位的候选人数量，由高到低');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!query.trim()) {
      setError('请输入查询内容');
      return;
    }
    
    setLoading(true);
    setError(null);
    
    try {
      const result = await processQuery(query);
      onQueryResult(result);
    } catch (err) {
      setError(err instanceof Error ? err.message : '处理查询时出错');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box component="form" onSubmit={handleSubmit} noValidate>
      <Grid container spacing={2} alignItems="flex-start">
        <Grid size={10}>
          <TextField
            fullWidth
            multiline
            rows={4}
            label="描述你想要查询的数据"
            placeholder="例如：查询每个岗位的候选人数量，由高到低"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
        </Grid>
        <Grid size={2} sx={{ justifyContent: 'center', alignItems: 'center', display: 'flex' }}>
          <Button
            type="submit"
            variant="contained"
            fullWidth
            sx={{ minHeight: '56px' }}
            endIcon={loading ? <CircularProgress size={20} color="inherit" /> : <SendIcon />}
            disabled={loading || !query.trim()}
          >
            {loading ? '处理中...' : '查询'}
          </Button>
        </Grid>
      </Grid>
      
      {error && (
        <Alert severity="error" sx={{ mt: 2 }}>
          {error}
        </Alert>
      )}
    </Box>
  );
};

export default QueryInput;